/*
 * 文件名：ShoppingCartServiceImpl.java
 * 版权：Copyright by hlst
 * 描述：
 * 修改人：liuziyu
 * 修改时间：2016年7月14日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package com.zcsy.manage.service.mall.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.constants.OwnerConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.mall.CouponDetail;
import com.zcsy.manage.model.mall.CouponInfo;
import com.zcsy.manage.model.mall.GoodsCollection;
import com.zcsy.manage.model.mall.GoodsInfo;
import com.zcsy.manage.model.mall.GoodsSpecification;
import com.zcsy.manage.model.mall.GoodsSpecificationAttr;
import com.zcsy.manage.model.mall.OrderDetailInfo;
import com.zcsy.manage.model.mall.OrderInfo;
import com.zcsy.manage.model.mall.OwnerAddress;
import com.zcsy.manage.model.mall.ShoppingCart;
import com.zcsy.manage.model.mall.vo.ShoppingCartVo;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.persistence.base.CommonConfigDao;
import com.zcsy.manage.persistence.mall.CouponDetailDao;
import com.zcsy.manage.persistence.mall.CouponInfoDao;
import com.zcsy.manage.persistence.mall.GoodsCollectionDao;
import com.zcsy.manage.persistence.mall.GoodsInfoDao;
import com.zcsy.manage.persistence.mall.GoodsSpecificationAttrDao;
import com.zcsy.manage.persistence.mall.GoodsSpecificationDao;
import com.zcsy.manage.persistence.mall.OrderInfoDao;
import com.zcsy.manage.persistence.mall.OwnerAddressDao;
import com.zcsy.manage.persistence.mall.ShoppingCartDao;
import com.zcsy.manage.persistence.weixin.StringUtil;
import com.zcsy.manage.service.base.IShopInfoService;
import com.zcsy.manage.service.mall.IGoodsCollectionService;
import com.zcsy.manage.service.mall.IGoodsInfoService;
import com.zcsy.manage.service.mall.IOrderInfoService;
import com.zcsy.manage.service.mall.IShoppingCartService;

@Service
public class ShoppingCartServiceImpl implements IShoppingCartService{
    
    public static final byte GROUP_SHOP = 1;
    public static final byte GROUP_DISE = 2;
    public static final byte GROUP_CONM = 3;
    
    private Map<String, List<ShoppingCart>> shopMap = null;
    private Map<String, List<ShoppingCart>> diseMap = null;
    private Map<String, List<ShoppingCart>> conmMap = null;
    
	@Autowired
	private GoodsInfoDao goodsInfoDao;
	
	@Autowired
	private ShoppingCartDao shoppingCartDao;
	
	@Autowired
	private GoodsSpecificationDao goodsSpecDao;
	
	@Autowired
	private GoodsSpecificationAttrDao goodsValueDao;
	
	@Autowired
	private OrderInfoDao orderInfoDao;
	
	@Autowired
	private OwnerAddressDao ownerAddressDao;

	@Autowired
    private IOrderInfoService orderService;
	
	@Autowired
	private CommonConfigDao commonConfigDao;
	
	@Autowired
	private IGoodsCollectionService collectionService;
	
	@Autowired
	private GoodsCollectionDao collectionDao;
	
	@Autowired
	private IShopInfoService shopInfoService;
	
	@Autowired
	private OwnerAddressDao addressDao;
	
	@Autowired
	private CouponInfoDao couponInfoDao;
	
	@Autowired
	private CouponDetailDao couponDeatilDao;
	
	@Autowired
	private IGoodsInfoService goodsInfoService;
	
	@Override
	public int addAmount(String cartId){
		return shoppingCartDao.addAmount(cartId, cartId);
	}
	
	@Override
	public int reduceAmount(String cartId){
		return shoppingCartDao.reduceAmount(cartId, cartId);
	}
	
	@Override
	public int setAmount(Map<String, Object> map){
		return shoppingCartDao.setAmount(map);
	}
	
	@Override
	public ShoppingCart getCartInfo(String cartId){
		return shoppingCartDao.getCartInfo(cartId);
	}
	
	@Override
	public int deleteByPrimaryKey(String cartId){
		return shoppingCartDao.deleteByPrimaryKey(cartId);
	}
	
	@Override
	public Integer getUserCartNum(String account){
		return shoppingCartDao.getUserCartNum(account);
	}
	
	@Override
	public Object addToCart(String userAccount, String goodsId,
			String specificationId, int amount,int type,GoodsInfo goods,GoodsSpecification spec,String cellId) {
		ShoppingCart cart = new ShoppingCart();
		cart.setUserAccount(userAccount);
		cart.setGoodsId(goodsId);
		cart.setCellId(cellId);
		if (!StringUtil.isEmptyString(specificationId) && !specificationId.equals("null")) {
			cart.setSpecificationId(specificationId);
		}
		Date date=new Date();
		cart.setSendTime(date);
		if (goods != null) {
			cart.setShopId(goods.getShopId());
			cart.setGoodsName(goods.getName());
			cart.setGoodsLogo(goods.getLogo());
			cart.setMarketPrice(goods.getMarketPrice());
		}
		cart.setAmount(amount);
		cart.setId(UniqueNumberUtils.get18UniqueNumber());
		return addToCart(cart,type, goods, spec);
	}

	public Object addToCart(ShoppingCart cart,int type,GoodsInfo goods,GoodsSpecification spec){
		
		
		if(type == OwnerConstants.CART_STATE_NORMAL){
		    
		    cart.setType(OwnerConstants.CART_STATE_NORMAL);
		    
		    ShoppingCart exists = shoppingCartDao.selectExistCart(cart);
	        //设置数量：已存在相同商品规格的,只加数量
	        if(exists != null){
	        	if (spec != null) {
	        		if(exists.getAmount()+cart.getAmount() > spec.getStock()){
	        			return OwnerConstants.NO_ENOUGH_GOODS;
	        		}else{
	        			exists.setAmount(exists.getAmount() + cart.getAmount());
	        		}
	        		
				}else {
					if(exists.getAmount()+cart.getAmount() > goods.getStock()){
						return OwnerConstants.NO_ENOUGH_GOODS;
					}else{
	        			exists.setAmount(exists.getAmount() + cart.getAmount());
	        		}
				}
	           
	            shoppingCartDao.updateCartAmount(exists);
	            return exists.getId();
	        }
		}else{
		    cart.setType(OwnerConstants.CART_STATE_FROMBUY);;
		}
		
		//设置价格：没有规格
		if(StringUtil.isEmptyString(cart.getSpecificationId())){
			cart.setPrice(goods.getPrice());
		}else{
			cart.setPrice(spec.getPrice());
			
			//设置规格描述
			Map map = new HashMap<String, Object>();
            map.put("goodsId", cart.getGoodsId());
            map.put("specificationId", cart.getSpecificationId());
            List<GoodsSpecificationAttr> goodsValues = goodsValueDao.getGoodsSpecAttrBySpecId(map);
            if(goodsValues != null){
            	StringBuffer buffer = new StringBuffer();
            	for(GoodsSpecificationAttr item : goodsValues){
            		if(item.getAttrValue() != null&&item.getAttrName() != null){
            			buffer.append(item.getAttrName()+":"+item.getAttrValue() + "，");
            		}else if(item.getAttributeValue() != null){
            			buffer.append(item.getAttributeValue() + "，");
            		}
            	}
            	
            	if(buffer.length() > 0){
            		cart.setMemo(buffer.substring(0, buffer.length() - 1).toString());
            	}
            }
		}
		
		//插入
		int result = shoppingCartDao.insertToCart(cart);
		if(cart.getId() != null){
			return cart.getId();
		}
		return result;
	}

	@Override
	public List<ShoppingCart> getSettleCarts(String[] ids) {
		List<ShoppingCart> carts =  shoppingCartDao.selectSettleCart(ids);
		
		return carts;
	}

	@Override
	public int delFromCart(String[] cIds) {
		return shoppingCartDao.delOwnerCart(cIds);
	}

    @Override
    public void addMyFavorite(String shopcartId, String goodsId, String userId) {
        // 添加购物车商品到收藏
        GoodsCollection collection = new GoodsCollection();
        collection.setId(UniqueNumberUtils.get18UniqueNumber());
        collection.setOwnerId(userId);
        collection.setGoodsId(goodsId);
        collection.setCollectionTime(DateUtils.getDate());
        
        collectionDao.insertCollection(collection);
        
        // 删除购物车中信息
        if(!StringUtil.isNullStr(shopcartId)){
        shoppingCartDao.deleteByPrimaryKey(shopcartId);
        }
    }

    @Override
    public int updateAmount(String shopcartId, String amount) {
        ShoppingCart shopcart = new ShoppingCart();
        shopcart.setId(shopcartId);
        shopcart.setAmount(Integer.parseInt(amount));
        
        return shoppingCartDao.updateCartAmount(shopcart);
    }

    public static void main(String[] args) {
        ShoppingCartServiceImpl service = new ShoppingCartServiceImpl();
//        service.confirmOrderFromShopcart("", null, null);
    }
    
    @Override
    public OrderInfo confirmOrderFromShopcart(String shopcartIds, User user, 
            List<OrderInfo> orderInfo, Integer type) {
        OrderInfo returnRe = new OrderInfo();
        try {
            
            List<ShoppingCart> shoppingCartList = shoppingCartDao.selectSettleCart(shopcartIds.split(","));
            
            // 按照 商铺ID、是否需要配送、是否需要商户确认进行拆单
            groupByType(shoppingCartList, GROUP_CONM); 
            
            /**
             * 生成订单规则
             * 1、购买商品中只有一类商品时，只生成二级订单
             * 2、拆单后含多个订单时，先生成一级订单，再生成二级订单
             */
            String tradeNo = UniqueNumberUtils.get18UniqueNumber();
            OrderInfo initInfo = orderInfo.get(0);
            // 1、
            if(conmMap.size() == 1) {
                for(String keyTemp : conmMap.keySet()) {
                    // 二级订单
                    OrderInfo bulidOrder = buildOrder(initInfo, initInfo.getCouponId(), conmMap.get(keyTemp), type);
                    
                    bulidOrder.setId(tradeNo);
                    String orderNo = UniqueNumberUtils.get16UniqueNumber();
                    returnRe.setOrderNumber(orderNo);
                    returnRe.setFinalPrice(bulidOrder.getFinalPrice());
                    
                    bulidOrder.setOrderNumber(orderNo);
                    bulidOrder.setShopId(initInfo.getShopId());
                    bulidOrder.setType(type);
                    bulidOrder.setState(Constants.ORDER_UNPAID);
                    bulidOrder.setCellId(user.getCurrentCell().getId());
                    
                    bulidOrder.setIsBySelf(initInfo.getIsBySelf());
                    bulidOrder.setDistributionType(Integer.parseInt(keyTemp.split("-")[1]));
                    bulidOrder.setIsNeedConfirm(Integer.parseInt(keyTemp.split("-")[2]));
                    
                    bulidOrder.setUserAccount(user.getLoginname());
                    bulidOrder.setShopMsg(initInfo.getShopMsg());
                    bulidOrder.setCreateTime(new Date());
                    bulidOrder.setExpectTime(initInfo.getExpectTime());
                    bulidOrder.setOrderLevel(Constants.INT_TWO);
                    
                    OwnerAddress address = addressDao.selectByPrimaryKey(initInfo.getRectAddrId());
                    bulidOrder.setContactor(address.getRecepientName());
                    bulidOrder.setContactorPhone(address.getRecepientPhone());
                    bulidOrder.setContactorAddress(address.getDetailAddress());
                    
                    orderService.insert(bulidOrder);
                    
                    // 生成订单详情
                    List<ShoppingCart> subList = conmMap.get(keyTemp);
                    OrderDetailInfo detailInfo = null;
                    for(ShoppingCart order : subList) {
                        detailInfo = new OrderDetailInfo();
                        detailInfo.setId(UniqueNumberUtils.get18UniqueNumber());
                        detailInfo.setLogo(order.getGoodsLogo());
                        detailInfo.setGoodsId(order.getGoodsId());
                        detailInfo.setShopId(order.getShopId());
                        detailInfo.setSpecificationId(order.getSpecificationId());
                        detailInfo.setPrice(order.getPrice());
                        detailInfo.setOrderId(tradeNo);
                        detailInfo.setAmount(order.getAmount());
                        detailInfo.setUserAccount(user.getLoginname());
                        detailInfo.setSendTime(new Date());
                        detailInfo.setGoodsName(order.getGoodsName());
                        detailInfo.setMarketPrice(order.getMarketPrice());
                        detailInfo.setMemo(order.getMemo());
                        
                        orderService.saveOrderDetail(detailInfo);
                    }
                    
                    // 更新优惠券状态
                    if(!StringUtil.isEmptyString(initInfo.getCouponId())) {
                        CouponDetail coupon = couponDeatilDao.selectByPrimaryKey(initInfo.getCouponId());
                        if(null != coupon) {
                            coupon.setState(Constants.COUPON_USED);
                            coupon.setUseTime(new Date());
                            couponDeatilDao.update(coupon);
                        }
                    }
                }
                
            } else { // 2、
                // 一级订单
                OrderInfo parentOrder = buildParentOrder(orderInfo, shoppingCartList, type);
                parentOrder.setId(tradeNo);
                
                String orderNo = UniqueNumberUtils.get16UniqueNumber();
                returnRe.setOrderNumber(orderNo);
                returnRe.setFinalPrice(parentOrder.getFinalPrice());
                
                parentOrder.setOrderNumber(orderNo);
                parentOrder.setState(Constants.ORDER_UNPAID);
                parentOrder.setCellId(user.getCurrentCell().getId());
                
                parentOrder.setUserAccount(user.getLoginname());
                parentOrder.setCreateTime(new Date());
                parentOrder.setOrderLevel(Constants.INT_ONE);
                
                OwnerAddress address = addressDao.selectByPrimaryKey(initInfo.getRectAddrId());
                parentOrder.setContactor(address.getRecepientName());
                parentOrder.setContactorPhone(address.getRecepientPhone());
                parentOrder.setContactorAddress(address.getDetailAddress());
                
                orderService.insert(parentOrder);
                
                boolean isShopSingle = true;
                String shopIds = "";
                for(String key : conmMap.keySet()) {
                    String[] param = key.split("-");
                    List<ShoppingCart> subList = conmMap.get(key);
                    
                    // 二级订单
                    OrderInfo subInfo = bulidItemOrder(orderInfo, conmMap,subList, type);;
                    subInfo.setId(UniqueNumberUtils.get18UniqueNumber());
                    subInfo.setOrderNumber(UniqueNumberUtils.get16UniqueNumber());
                    subInfo.setParentId(parentOrder.getId());
                    subInfo.setState(Constants.ORDER_UNPAID);
                    subInfo.setOrderLevel(Constants.INT_TWO);
                    subInfo.setShopId(param[0]);
                    subInfo.setType(type);
                    subInfo.setCellId(user.getCurrentCell().getId());
                    
                    subInfo.setDistributionType(Integer.parseInt(param[1]));
                    subInfo.setIsNeedConfirm(Integer.parseInt(param[2]));
                    
                    subInfo.setUserAccount(user.getLoginname());
                    subInfo.setShopMsg(initInfo.getShopMsg());
                    subInfo.setCreateTime(new Date());
                    subInfo.setExpectTime(initInfo.getExpectTime());
                    
                    subInfo.setContactor(address.getRecepientName());
                    subInfo.setContactorPhone(address.getRecepientPhone());
                    subInfo.setContactorAddress(address.getDetailAddress());
                    
                    orderService.insert(subInfo);
                    
                    OrderDetailInfo detailInfo = null;
                    for(ShoppingCart order : subList) {
                        detailInfo = new OrderDetailInfo();
                        detailInfo.setId(UniqueNumberUtils.get18UniqueNumber());
                        detailInfo.setLogo(order.getGoodsLogo());
                        detailInfo.setGoodsId(order.getGoodsId());
                        detailInfo.setShopId(order.getShopId());
                        detailInfo.setSpecificationId(order.getSpecificationId());
                        detailInfo.setPrice(order.getPrice());
                        detailInfo.setAmount(order.getAmount());
                        detailInfo.setOrderId(subInfo.getId());
                        detailInfo.setUserAccount(user.getLoginname());
                        detailInfo.setSendTime(new Date());
                        detailInfo.setGoodsName(order.getGoodsName());
                        detailInfo.setMarketPrice(order.getMarketPrice());
                        detailInfo.setMemo(order.getMemo());
                        
                        orderService.saveOrderDetail(detailInfo);
                    }
                    
                    //如果子订单都是一个店铺的
                    if(!StringUtils.isEmpty(subInfo.getShopId())){
                        if(StringUtils.isEmpty(shopIds)){
                            shopIds = subInfo.getShopId();
                        }else if(!shopIds.equals(subInfo.getShopId())){
                            isShopSingle = false;
                        }
                    }
                    
                    // 更新优惠券状态
                    if(!StringUtil.isEmptyString(subInfo.getCouponId())) {
                        CouponDetail coupon = couponDeatilDao.selectByPrimaryKey(subInfo.getCouponId());
                        if(null != coupon) {
                            coupon.setState(Constants.COUPON_USED);
                            coupon.setUseTime(new Date());
                            couponDeatilDao.update(coupon);
                        }
                    }
                    
                }
                
                //如果子订单都是一个店铺的
                if(isShopSingle && !StringUtils.isEmpty(shopIds)){
                    parentOrder.setShopId(shopIds);
                    orderService.update(parentOrder);
                }
            }
            
            // 更新库存
            goodsInfoService.updateGoodsStockAndSalesOrder(shoppingCartList);
            
            /**
             * 删除购物车信息
             */
            for(String cartId : shopcartIds.split(",")){
                deleteByPrimaryKey(cartId);
            }
            returnRe.setId(tradeNo);
            
            // 支付价格为零的情况下，直接修改订单状态
            if(BigDecimal.ZERO.compareTo(returnRe.getFinalPrice()) >= 0) {
                orderService.payOrder(returnRe.getOrderNumber(), null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            clearMap();
        }
        return returnRe;
    }
    
    @Override
    public List<ShoppingCartVo> castShoopingCartVo(List<ShoppingCart> list, int goodsType){
    	List<ShoppingCartVo> voList = new ArrayList<>();
        try {
	        BigDecimal carriageLine = BigDecimal.ZERO;
	        BigDecimal carriageLineY = BigDecimal.ZERO;
	        BigDecimal carriageLineN = BigDecimal.ZERO;
	        switch (goodsType) {
	        case Constants.GOODS_TYPE_NORMAL:
	        	carriageLine = new BigDecimal(commonConfigDao.getByName("normal_carriage_line").getValue());
	        	carriageLineY = new BigDecimal(commonConfigDao.getByName("normal_carriage_y").getValue());
	        	carriageLineN = new BigDecimal(commonConfigDao.getByName("normal_carriage_n").getValue());
	        	break;
	        case Constants.GOODS_TYPE_SECKILL:
	            carriageLineN = new BigDecimal(commonConfigDao.getByName("seckill_carriage").getValue());
	        	break;
	        case Constants.GOODS_TYPE_CARDS:
	            carriageLineN = new BigDecimal(commonConfigDao.getByName("cards_carriage").getValue());
	        	break;
	        	
	        default:
	        	break;
	        }
	        
	        // 商铺定单总额
	        Map<String, BigDecimal> shopCount = new HashMap<>();
	        
	        // 减免配送费
	        Map<String, BigDecimal> derateCarriage = new HashMap<>();
	        
	        // 原配送费
	        Map<String, BigDecimal> carriageMap = new HashMap<>();
	        
	        // 拆单计算运费
	        groupByType(list, GROUP_CONM);
	        
	        for(String key : conmMap.keySet()) {
	        	String[] temp = key.split("-");
	        	String shopId = temp[0];
	        	String isNeedDise = temp[1];
	        	
	        	BigDecimal subTotal = getOrderTotal(conmMap.get(key));
	        	
	        	// 秒杀、积分商品不存在商铺id
	        	if(StringUtil.isEmptyString(shopId) || "null".equals(shopId)) {
	        	    shopId = Constants.ID_ZERO;
	        	}
	        	// 商铺定单总额
	        	if(shopCount.containsKey(shopId)) {
	        		shopCount.put(shopId, shopCount.get(shopId).add(subTotal));
	        	} else {
	        		shopCount.put(shopId, subTotal);
	        	}
	        	
	        	if(carriageMap.containsKey(shopId)) {
	        		if(Constants.STATE_ENABLED == Integer.parseInt(isNeedDise)) {
	        			carriageMap.put(shopId, carriageMap.get(shopId).add(carriageLineN));
	        			// 正常商品才享受配送费减免
	        			if(Constants.GOODS_TYPE_NORMAL == goodsType) {
	        			    if(subTotal.compareTo(carriageLine) >= 0) {
	                            derateCarriage.put(shopId, derateCarriage.get(shopId).add(carriageLineY));
	                        } else {
	                            derateCarriage.put(shopId, derateCarriage.get(shopId).add(carriageLineN));
	                        }  
	        			} else {
	        			    derateCarriage.put(shopId, carriageLineN);
	        			}
	        			
	        		}
	        	} else {
	        		if(Constants.STATE_ENABLED == Integer.parseInt(isNeedDise)) {
	        			carriageMap.put(shopId, carriageLineN);
	        			// 正常商品才享受配送费减免
	        			if(Constants.GOODS_TYPE_NORMAL == goodsType) {
	        			    if(subTotal.compareTo(carriageLine) >= 0) {
	        			        derateCarriage.put(shopId, carriageLineY);
	        			    } else {
	        			        derateCarriage.put(shopId, carriageLineN);
	        			    }
	        			} else {
	        			    derateCarriage.put(shopId, carriageLineN); 
	        			}
	        		} else {
	        			carriageMap.put(shopId, BigDecimal.ZERO);
	        			derateCarriage.put(shopId, BigDecimal.ZERO);
	        		}
	        	}
	        }
	        
	        ShoppingCartVo vo = null;
	        for(ShoppingCart cart : list) {
	        	boolean flag = true;
	        	for(ShoppingCartVo vl : voList) {
	        		if(cart.getShopId().equals(vl.getShopId())) {
	        			vl.getGoodsList().add(cart);
	        			flag = false;
	        			break;
	        		}
	        	}
	        	if(flag) {
	        		vo = new ShoppingCartVo(cart);
	        		if(StringUtil.isEmptyString(cart.getShopId())) {
	        		    cart.setShopId(Constants.ID_ZERO);
	        		} 
	        		vo.setCarriage(carriageMap.get(cart.getShopId()));
                    vo.setDerateCarriage(derateCarriage.get(cart.getShopId()));
                    vo.setSubTotal(shopCount.get(cart.getShopId()));
	        		vo.setDerateLine(carriageLine);
	        		// 当前用户店铺优惠券
	        		voList.add(vo);
	        	}
	        }
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			clearMap();
		}
        
        return voList;
    }
   
    
    @Override
    public void confirmOrderByGoodsId(String goodsIds) {}
    
    private BigDecimal getOrderTotal(List<ShoppingCart> list) {
        BigDecimal result = BigDecimal.ZERO;
        for(ShoppingCart goods : list) {
            result = result.add(goods.getSubTotal());
        }
        return result;
    }

    private void groupByType(List<ShoppingCart> list, byte type){
        List<ShoppingCart> confirmShoppingCart = null;
        switch (type) {
        case GROUP_SHOP:
            for(ShoppingCart order : list) {
                String orderId = order.getShopId();
                confirmShoppingCart = new ArrayList<>();
                if(null == shopMap) {
                    shopMap = new HashMap<>();
                    confirmShoppingCart.add(order);
                    shopMap.put(orderId, confirmShoppingCart);
                } else {
                    if(shopMap.containsKey(orderId)){
                        putSubshopMap(shopMap, orderId, order);
                    } else {
                        orderId = UniqueNumberUtils.get18UniqueNumber();
                        confirmShoppingCart.add(order);
                        shopMap.put(orderId, confirmShoppingCart);
                    }
                }
            }
            break;
        case GROUP_DISE:
            for(ShoppingCart order : list) {
                String orderId = order.getShopId() + "-"+ order.getIsNeedDistribute();
                confirmShoppingCart = new ArrayList<>();
                if(null == diseMap) {
                    diseMap = new HashMap<>();
                    confirmShoppingCart.add(order);
                    diseMap.put(orderId, confirmShoppingCart);
                } else {
                    if(diseMap.containsKey(orderId)){
                        putSubshopMap(diseMap, orderId, order);
                    } else {
                        orderId = UniqueNumberUtils.get18UniqueNumber();
                        confirmShoppingCart.add(order);
                        diseMap.put(orderId, confirmShoppingCart);
                    }
                }
            }
            break;
        case GROUP_CONM:
            for(ShoppingCart order : list) {
                String orderId = order.getShopId() + "-" + order.getIsNeedDistribute() + "-" + order.getIsNeedConfirm();
                confirmShoppingCart = new ArrayList<>();
                if(null == conmMap) {
                    conmMap = new HashMap<>();
                    confirmShoppingCart.add(order);
                    conmMap.put(orderId, confirmShoppingCart);
                } else {
                    if(conmMap.containsKey(orderId)){
                        putSubshopMap(conmMap, orderId, order);
                    } else {
                        confirmShoppingCart.add(order);
                        conmMap.put(orderId, confirmShoppingCart);
                    }
                }
            }
            break;
        default:
            break;
        }
    }
    
    private Map<String, List<ShoppingCart>> groupOrder(List<ShoppingCart> list){
        Map<String, List<ShoppingCart>> resultMap = new HashMap<>();
        List<ShoppingCart> confirmShoppingCart = null;
        for(ShoppingCart order : list) {
            String orderId = order.getShopId() + "-" + order.getIsNeedDistribute() + "-" + order.getIsNeedConfirm();
            if(resultMap.containsKey(orderId)){
                resultMap.get(orderId).add(order);
            } else {
                confirmShoppingCart = new ArrayList<>();
                confirmShoppingCart.add(order);
                resultMap.put(orderId, confirmShoppingCart);
            }
        }
        return resultMap;
    }
    
    private void putSubshopMap(Map<String, List<ShoppingCart>> map, String orderId, ShoppingCart ShoppingCart) {
        map.get(orderId).add(ShoppingCart);
    }
    
    private void clearMap(){
        if(null != shopMap) {
            shopMap.clear();
            shopMap = null;
        }
        if(null != diseMap) {
            diseMap.clear();
            diseMap = null;
        }
        if(null != conmMap) {
            conmMap.clear();
            conmMap = null;
        }
    }

    
    @Override
    public List<ShoppingCart> queryShoppingCart(String userAccount, String cellId) {
        return shoppingCartDao.queryShoppingCart(userAccount, cellId);
    }

	@Override
	public int insertToCart(ShoppingCart cart) {
		return shoppingCartDao.insertToCart(cart);
	}
	
	/**
	 * 生成一级订单信息
	 * @Method: buildParentOrder
	 * @Description 能拆出多个订单或者多个商铺
	 * @param orderInfo 用户选择界面初始化信息：是否自提、优惠卷
	 * @param cartList 购物车信息
	 * @param goodsType 商品类别
	 */
    private OrderInfo buildParentOrder(List<OrderInfo> orderInfo, List<ShoppingCart> cartList, int goodsType) {
        OrderInfo result = new OrderInfo();
        Map<String, List<ShoppingCart>> cartMap = groupOrder(cartList);
        Map<String, OrderInfo> initMap = new HashMap<>();
        for (OrderInfo order : orderInfo) {
            initMap.put(order.getShopId(), order);
        }
        
        BigDecimal orderTotal = BigDecimal.ZERO; // 订单总金额
        BigDecimal couponAmount = BigDecimal.ZERO; // 优惠总金额
        BigDecimal carriageAmount = BigDecimal.ZERO; // 订单总运费
        
        for (ShoppingCart cart : cartList) {
            orderTotal = orderTotal.add(cart.getSubTotal());
        }
        
        String couponId = orderInfo.get(0).getCouponId();
        if (!StringUtil.isEmptyString(couponId)) {
            for (String id : couponId.split(",")) {
                CouponInfo coupon = couponInfoDao.getCoupontInfoByDetailId(id);
                couponAmount = couponAmount.add(coupon.getBreakPrice());
            }
        }
        
        for (String key : cartMap.keySet()) {
            String shopId = key.split("-")[0];
            carriageAmount = carriageAmount.add(getCarriage(initMap.get(shopId), cartMap.get(key), goodsType));
        }
        
        result.setTotalPrice(orderTotal);
        if(!StringUtil.isEmptyString(couponId) && couponId.split(",").length == 1) {
            result.setCouponId(couponId); 
        }
        result.setCouponPrice(couponAmount);
        result.setCarriage(carriageAmount);
        result.setFinalPrice(orderTotal.subtract(couponAmount).add(carriageAmount));
        
        result.setType(goodsType);
        result.setState(Constants.ORDER_UNPAID);
        return result;
        
    }
    
    /**
     * 生成二级子订单
     * @Method: bulidItemOrder
     * @param orderInfo 用户界面选择信息  优惠券、自提、留言、期望收货时间，以店铺为单位
     * @param cartMap   拆单后的所有订单信息
     * @param cartList  二级订单包含信息
     * @param goodsType 商品类别
     */
    private OrderInfo bulidItemOrder(List<OrderInfo> orderInfo, Map<String, List<ShoppingCart>> cartMap,
            List<ShoppingCart> cartList, int goodsType){
        OrderInfo result = new OrderInfo();
        
        // 根据商铺id获取用户界面选择信息
        OrderInfo initInfo = null;
        for(OrderInfo info : orderInfo) {
            if(info.getShopId().equals(cartList.get(0).getShopId())){
                initInfo = info;
                break;
            }
        }
        
        BigDecimal orderTotal = BigDecimal.ZERO; // 订单总金额
        BigDecimal couponAmount = BigDecimal.ZERO; // 优惠总金额
        BigDecimal carriageAmount = BigDecimal.ZERO; // 订单总运费
        String couponId = ""; // 优惠券id

        for(ShoppingCart cart : cartList) {
            orderTotal = orderTotal.add(cart.getSubTotal());
        }
        
        /**
         * 根据用户选择的优惠券计算订单优惠信息
         * 1、平台券  -- 优惠券金额/总订单数  优惠券金额 * 订单金额 / 订单总金额
         * 2、商铺券 -- 优惠券金额/店铺内订单数
         */
        Map<String, CouponInfo> couponMap = new HashMap<>();
        if(Constants.GOODS_TYPE_NORMAL == goodsType) {
            String tempId = initInfo.getCouponId();
            if(!StringUtil.isEmptyString(tempId)){
            for (String id : tempId.split(",")) {
                CouponInfo coupon = couponInfoDao.getCoupontInfoByDetailId(id);
                coupon.setCouponDetailId(id);
                if(Constants.COUPON_TYPE_FORUM == coupon.getUserAccountType()) {
                    couponMap.put(null, coupon);
                } else {
                    couponMap.put(coupon.getShopId(), coupon);
                }
            }
            }
        }
        for(String key : couponMap.keySet()) {
            if(StringUtil.isEmptyString(key)) { // 平台券
                couponAmount = couponMap.get(key).getBreakPrice().multiply(orderTotal).divide(
                        getOrderTotalAmount(cartMap), 2, BigDecimal.ROUND_HALF_UP);
//                couponAmount = couponMap.get(key).getBreakPrice().divide(
//                        new BigDecimal(getOrderTotal(cartMap)), 2, BigDecimal.ROUND_HALF_UP);
                couponId = couponMap.get(key).getCouponDetailId();
            } else { // 商铺券
                String shopId = couponMap.get(key).getShopId();
                if(shopId.equals(cartList.get(0).getShopId())) {
                    couponAmount = couponMap.get(key).getBreakPrice().divide
                            (new BigDecimal(getShopOrderTotal(cartMap, shopId)), 2, BigDecimal.ROUND_HALF_UP);
                    couponId = couponMap.get(key).getCouponDetailId();
                }
            }
        }
        
        // 配送费
        carriageAmount = getCarriage(initInfo, cartList, goodsType);
        
        result.setCouponId(couponId);
        result.setCouponPrice(couponAmount);
        result.setTotalPrice(orderTotal);
        result.setCarriage(carriageAmount);
        result.setFinalPrice(orderTotal.subtract(couponAmount).add(carriageAmount));
        result.setIsBySelf(initInfo.getIsBySelf());
        return result;
    }
	/**
	 * 生成订单基本信息
	 * @Method: buildOrder
	 * @Description 
	 * @param initInfo
	 * @param cartList
	 */
	private OrderInfo buildOrder(OrderInfo initInfo, String couponId, List<ShoppingCart> cartList, int goodsType) {
	    OrderInfo order = new OrderInfo();
	    
	    BigDecimal orderTotal = BigDecimal.ZERO;
	    BigDecimal couponAmount = BigDecimal.ZERO;
	    BigDecimal carriageAmount = BigDecimal.ZERO;

	    for(ShoppingCart cart : cartList) {
	        orderTotal = orderTotal.add(cart.getSubTotal());
	    }
	    
	    if(!StringUtil.isEmptyString(couponId)) {
	        CouponInfo coupon = couponInfoDao.getCoupontInfoByDetailId(couponId);
	        couponAmount = coupon.getBreakPrice();
	    }
	    carriageAmount = getCarriage(initInfo, cartList, goodsType);
	    
	    order.setCouponId(couponId);
	    order.setCouponPrice(couponAmount);
	    order.setTotalPrice(orderTotal);
	    order.setCarriage(carriageAmount);
	    if(Constants.GOODS_TYPE_CARDS == goodsType) {
	        order.setFinalPrice(carriageAmount);
	        order.setCostIntegral(orderTotal.intValue());
	    } else {
	        order.setFinalPrice(orderTotal.subtract(couponAmount).add(carriageAmount));
	    }
	    
	    return order;
	}
	
	/**
	 * 根据用户先把自提及商品是否支持配送计算运费信息
	 * @Method: getCarriage
	 * @param initInfo  用户选择信息
	 * @param cartList  订单信息
	 * @param goodsType 商品类型
	 */
	private BigDecimal getCarriage(OrderInfo initInfo, List<ShoppingCart> cartList, int goodsType){
	    
	    BigDecimal result = BigDecimal.ZERO;
	    try {
	        /**
	         * 各个类别下的运费
	         */
            BigDecimal carriageLine = BigDecimal.ZERO;
            BigDecimal carriageLineY = BigDecimal.ZERO;
            BigDecimal carriageLineN = BigDecimal.ZERO;
            switch (goodsType) {
            case Constants.GOODS_TYPE_NORMAL:
                carriageLine = new BigDecimal(commonConfigDao.getByName("normal_carriage_line").getValue());
                carriageLineY = new BigDecimal(commonConfigDao.getByName("normal_carriage_y").getValue());
                carriageLineN = new BigDecimal(commonConfigDao.getByName("normal_carriage_n").getValue());
                break;
            case Constants.GOODS_TYPE_SECKILL:
                carriageLineN = new BigDecimal(commonConfigDao.getByName("seckill_carriage").getValue());
                break;
            case Constants.GOODS_TYPE_CARDS:
                carriageLineN = new BigDecimal(commonConfigDao.getByName("cards_carriage").getValue());
                break;
            default:
                break;
            }
            
            // 商品是否支持配送
            int isNeedDise = cartList.get(0).getIsNeedDistribute();
            
            // 订单总额
            BigDecimal subTotal = getOrderTotal(cartList);
            
            /**
             * 商品支持配 && 用户选择配送 && 订单金额满足减免线
             */
            if(Constants.IS_HAS_DISN_Y == isNeedDise) {
             // 正常商品才享受配送费减免
                if(Constants.GOODS_TYPE_NORMAL == goodsType) {
                    if(Constants.IS_BYSELF_N == initInfo.getIsBySelf()) {
                        if(subTotal.compareTo(carriageLine) >= 0) {
                            result = result.add(carriageLineY);
                        } else {
                            result = result.add(carriageLineN);  
                        }
                    }
                } else {
                    if(Constants.IS_BYSELF_N == initInfo.getIsBySelf()) {
                        result = result.add(carriageLineN);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
	}
	
	/**
	 * 拆单后所有订单的数量
	 * @Method: getOrderTotal
	 * @param cartMap
	 */
	private int getOrderTotal(Map<String, List<ShoppingCart>> cartMap) {
	    int orderTotal = 0;
	    for(String key : cartMap.keySet()) {
	        orderTotal = orderTotal + cartMap.get(key).size();
	    }
	    return orderTotal;
	}
	
	/**
     * 拆单后所有订单的总金额
     * @Method: getOrderTotal
     * @param cartMap
     */
    private BigDecimal getOrderTotalAmount(Map<String, List<ShoppingCart>> cartMap) {
        BigDecimal totalAmount = BigDecimal.ZERO;
        for(String key : cartMap.keySet()) {
            for(ShoppingCart cat : cartMap.get(key)) {
                totalAmount = totalAmount.add(cat.getSubTotal());
            }
        }
        return totalAmount;
    }
	
	/**
     * 拆单后所有商铺订单的数量
     * @Method: getShopOrderTotal
     * @param cartMap
     */
	private int getShopOrderTotal(Map<String, List<ShoppingCart>> cartMap, String shopId) {
        int shopOrderTotal = 0;
        for(String key : cartMap.keySet()) {
            String temp = key.split("-")[0];
            if(shopId.equals(temp)) {
//                shopOrderTotal = shopOrderTotal + cartMap.get(key).size();
                shopOrderTotal ++ ;
            }
        }
        return shopOrderTotal;
    }
	
	@Override
	public RequestJson checkSubmitOrder(List<ShoppingCart> cartList, User user){
		RequestJson result = new RequestJson();
		
		if(cartList == null || cartList.size() == 0){
    		result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
    		result.setMsg("商品已全部失效，请重新购买!");
    		result.setSuccess(false);
    		return result;
    	}
    	for(ShoppingCart item : cartList){
        	if(item.isDisable()){
        		result.setMsg(item.getGoodsName() + "商品已失效，请重新购买！");
                result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                result.setSuccess(false);
                return result;
        	}
        	
        	//选了规格但是没查到相应规格
        	if(item.getSpecificationId() != null
        			&& item.getSpectificationId() == null){
        		result.setMsg(item.getGoodsName() + "商品规格已失效，请重新购买！");
                result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                result.setSuccess(false);
                return result;
        	}
        	
        	if(item.getStock() < item.getAmount().intValue()){
        		result.setMsg(item.getGoodsName() + "商品库存不够了，下次早点来哦！");
                result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                result.setSuccess(false);
                return result;
        	}
        	
        	if(item.getGoodsType() == Constants.GOODS_TYPE_SECKILL){
        		Date now = new Date();
        		if(item.getKillStartTime().compareTo(now) > 0){
        			result.setMsg("秒杀还没开始，请耐心等候！");
                    result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                    result.setSuccess(false);
                    return result;
        		}
        		if(item.getKillEndTime().compareTo(now) < 0){
        			result.setMsg("秒杀时间已过，下次早点来哦！");
                    result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                    result.setSuccess(false);
                    return result;
        		}
        	}else if(item.getGoodsType() == Constants.GOODS_TYPE_CARDS){
        		if(user.getIntegral() == null || user.getIntegral().intValue() < (item.getIntegralNum() * item.getAmount())){
        			result.setMsg("积分不够，攒够积分再来吧");
                    result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                    result.setSuccess(false);
                    return result;
        		}
        	}
        	
        	//平台商品设置店铺为D生活
        	if(StringUtils.isEmpty(item.getShopId())){
        		item.setShopName(Constants.DLIFE);
        	}
        }
		
		return null;
	}
}
